/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.controller;

import com.minierp.bean.PurchaseBillBean;
import com.minierp.bean.UserBean;
import com.minierp.dao.AdjustBillDao;
import com.minierp.dao.BankAccountBalanceDao;
import com.minierp.dao.BankAccountDao;
import com.minierp.dao.CodeRuleDao;
import com.minierp.dao.IdGenerator;
import com.minierp.dao.PayBillDao;
import com.minierp.dao.ProductDao;
import com.minierp.dao.PurchaseBillDao;
import com.minierp.dao.PurchaseBillItemDao;
import com.minierp.dao.SerialNumberDao;
import com.minierp.dao.StockBalanceDao;
import com.minierp.dao.StockDao;
import com.minierp.dao.StorehouseDao;
import com.minierp.err.PermissionDennyException;
import com.minierp.err.StockNoEnoughException;
import com.minierp.helper.EncCommonHelper;
import com.minierp.helper.EncPurchaseBillFormCtrHelper;
import com.minierp.helper.PageHelper;
import com.minierp.model.CodeRule;
import com.minierp.model.EnterpriseInfo;
import com.minierp.model.Establishment;
import com.minierp.model.PurchaseBill;
import com.minierp.model.PurchaseBillExt;
import com.minierp.model.PurchaseBillItem;
import com.minierp.model.Storehouse;
import com.minierp.model.TallySet;
import com.minierp.service.PurchaseBillService;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.springframework.dao.CannotAcquireLockException;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

public class PurchaseBillFormCtr extends SimpleFormController {
	private BankAccountDao bankAccountDao;
	private PurchaseBillItemDao purchaseBillItemDao;
	private PurchaseBillDao purchaseBillDao;
	private CodeRuleDao codeRuleDao;
	private SerialNumberDao serialNumberDao;
	private StorehouseDao storehouseDao;
	private ProductDao productDao;
	private StockDao stockDao;
	private StockBalanceDao stockBalanceDao;
	private BankAccountBalanceDao bankAccountBalanceDao;
	private PayBillDao payBillDao;
	private AdjustBillDao adjustBillDao;
	private IdGenerator idGenerator;
	private PurchaseBillService purchaseBillService;
	private DataSource dataSource;

	protected Map referenceData(HttpServletRequest request) throws Exception {
		HashMap refData = new HashMap();
		String id = request.getParameter("id");
		if (id == null) {
			id = "";
		}

		refData.put("id", id);
		refData.put("alertType", request.getParameter("alert_type"));
		List baList = this.bankAccountDao.getList("", "");
		EnterpriseInfo ent = EncCommonHelper.getEnterpriseInfo(request);
		UserBean ub = EncCommonHelper.getCurrentUserAccount(request);
		long dfTsId = 0L;
		long specId = 0L;
		if (id != null && !id.equals("")) {
			PurchaseBill bb = (PurchaseBill) this.purchaseBillDao.get(
					PurchaseBill.class, Long.parseLong(id));
			specId = bb.getBankAccountId();
			dfTsId = bb.getTallySetId();
		} else {
			dfTsId = ub.getUser().getDfTsId();
		}

		refData.put("bankAccountList",
				PageHelper.parseBaList(baList, ent, ub, dfTsId, specId));
		refData.put("storehouseList", this.storehouseDao.getList(false));
		return refData;
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		String id = request.getParameter("id");
		PurchaseBillBean form;
		String type;
		if (id != null && !id.equals("")) {
			PurchaseBill arg13 = (PurchaseBill) this.purchaseBillDao.get(
					PurchaseBill.class, Long.parseLong(id));
			PurchaseBillExt arg15 = (PurchaseBillExt) this.purchaseBillDao.get(
					PurchaseBillExt.class, Long.parseLong(id));
			if (arg13 == null) {
				throw new Exception("Record not found for id:" + id);
			}

			Establishment arg17 = (Establishment) this.purchaseBillDao.get(
					Establishment.class, arg13.getProviderId());
			TallySet arg18 = (TallySet) this.purchaseBillDao.get(
					TallySet.class, arg13.getTallySetId());
			List arg20 = this.purchaseBillItemDao.getList(arg13.getId());
			long[] arg21 = new long[arg20.size()];

			for (int arg23 = 0; arg23 < arg20.size(); ++arg23) {
				arg21[arg23] = ((PurchaseBillItem) arg20.get(arg23))
						.getProductId();
			}

			List arg24 = this.productDao.getList(arg21);
			form = EncPurchaseBillFormCtrHelper.doFormBackingObjectEdit(arg13,
					arg15, arg17, arg18, arg20, arg24);
		} else {
			type = request.getParameter("template_id");
			String providerId;
			Establishment est;
			List storehouseList;
			if (type != null && !type.equals("")) {
				PurchaseBill arg14 = (PurchaseBill) this.purchaseBillDao.get(
						PurchaseBill.class, Long.parseLong(type));
				if (arg14 == null) {
					throw new Exception(
							"Template PurchaseBill not found for id " + type);
				}

				providerId = arg14.getBillType();
				if (providerId != null && providerId.equals("BUY")) {
					if (!EncCommonHelper.checkPrivilege(request, "PURC_BUY")) {
						throw new PermissionDennyException("Permission Denny");
					}
				} else if (providerId != null
						&& providerId.equals("BACK")
						&& !EncCommonHelper
								.checkPrivilege(request, "PURC_BACK")) {
					throw new PermissionDennyException("Permission Denny");
				}

				est = (Establishment) this.purchaseBillDao.get(
						Establishment.class, arg14.getProviderId());
				TallySet arg19 = (TallySet) this.purchaseBillDao.get(
						TallySet.class, arg14.getTallySetId());
				List itemList = this.purchaseBillItemDao.getList(arg14.getId());
				long[] arg22 = new long[itemList.size()];

				for (int arg25 = 0; arg25 < itemList.size(); ++arg25) {
					arg22[arg25] = ((PurchaseBillItem) itemList.get(arg25))
							.getProductId();
				}

				storehouseList = this.productDao.getList(arg22);
				form = EncPurchaseBillFormCtrHelper
						.doFormBackingObjectTemplate(request, arg14, est,
								arg19, itemList, storehouseList);
			} else {
				String cr = request.getParameter("type");
				if (cr != null && cr.equals("BUY")) {
					if (!EncCommonHelper.checkPrivilege(request, "PURC_BUY")) {
						throw new PermissionDennyException("Permission Denny");
					}
				} else if (cr != null
						&& cr.equals("BACK")
						&& !EncCommonHelper
								.checkPrivilege(request, "PURC_BACK")) {
					throw new PermissionDennyException("Permission Denny");
				}

				providerId = request.getParameter("provider_id");
				est = null;
				if (providerId != null && !providerId.equals("")) {
					est = (Establishment) this.purchaseBillDao.get(
							Establishment.class, Long.parseLong(providerId));
				}

				long storehouseId = 0L;
				UserBean ub = EncCommonHelper.getCurrentUserAccount(request);
				storehouseList = this.storehouseDao.getList(ub);

				for (int i = 0; i < storehouseList.size(); ++i) {
					Storehouse sto = (Storehouse) storehouseList.get(0);
					if (sto.getTallySetId() == ub.getUser().getDfTsId()) {
						storehouseId = sto.getId();
						break;
					}
				}

				form = EncPurchaseBillFormCtrHelper.doFormBackingObjectNew(
						request, cr, est, storehouseId);
			}
		}

		type = form.getPurchaseBill().getBillType();
		CodeRule arg16 = null;
		if (type != null && type.equals("BUY")) {
			arg16 = this.codeRuleDao.get("PURCHASE_BILL_BUY");
		} else if (type != null && type.equals("BACK")) {
			arg16 = this.codeRuleDao.get("PURCHASE_BILL_BACK");
		}

		if (arg16 == null) {
			throw new Exception("Code rule not found!");
		} else {
			form.setCodeRule(arg16);
			return form;
		}
	}

	protected void onBind(HttpServletRequest request, Object command)
			throws Exception {
		PurchaseBillBean form = (PurchaseBillBean) command;
		EncPurchaseBillFormCtrHelper.doOnBind(request, form, this.dataSource);
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		ModelAndView mv = new ModelAndView(this.getSuccessView());
		String id = request.getParameter("id");
		String examine = request.getParameter("examine");
		String alertMsg = "";
		PurchaseBillBean form = (PurchaseBillBean) command;
		PurchaseBill obj = form.getPurchaseBill();
		UserBean ub = EncCommonHelper.getCurrentUserAccount(request);
		EnterpriseInfo ent = EncCommonHelper.getEnterpriseInfo(request);
		if (examine != null && examine.equals("1")) {
			String multipartRequest = "";
			if (obj.getBillType().equals("BUY")) {
				multipartRequest = "PURC_BUY_EXAM";
			} else {
				multipartRequest = "PURC_BACK_EXAM";
			}

			if (!EncCommonHelper.checkPrivilege(request, multipartRequest)) {
				throw new Exception("Permission deny!");
			}
		}

		MultipartHttpServletRequest multipartRequest1 = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = multipartRequest1.getFile("attach_file");
		String continueFlag;
		String alertType;
		if (multipartFile != null && !multipartFile.isEmpty()) {
			continueFlag = multipartFile.getOriginalFilename();
			alertType = EncCommonHelper.getExtendName(continueFlag);
			String uploadPath = EncCommonHelper.getUploadVirtualPath(this
					.getServletContext());
			String realPath = this.getServletContext().getRealPath(uploadPath);
			String fileName = ub.getUser().getId() + "_"
					+ System.currentTimeMillis() + "." + alertType;
			FileCopyUtils.copy(multipartFile.getBytes(), new File(realPath
					+ System.getProperty("file.separator") + fileName));
			obj.setAttachFile(uploadPath + fileName);
		}

		if (id != null && !id.equals("")) {
			if (obj.getBillType().equals("BUY")) {
				continueFlag = "PURC_BUY";
			} else {
				continueFlag = "PURC_BACK";
			}

			if (!EncCommonHelper.checkPrivilege(request, continueFlag)) {
				throw new Exception("Permission deny!");
			}

			try {
				this.purchaseBillService.txUpdate(form, examine, ub, ent,
						this.purchaseBillDao, this.purchaseBillItemDao,
						this.payBillDao, this.adjustBillDao,
						this.bankAccountBalanceDao, this.stockDao,
						this.stockBalanceDao, this.idGenerator);
			} catch (StockNoEnoughException arg19) {
				EncCommonHelper.setAlertMessage(request, arg19.getMessage());
				return this.showForm(request, errors, this.getFormView());
			} catch (CannotAcquireLockException arg20) {
				EncCommonHelper.setAlertMessage(request, "事务冲突故障，请重新操作！");
				return this.showForm(request, errors, this.getFormView());
			}

			alertMsg = "修改成功！";
		} else {
			try {
				this.purchaseBillService.txInsert(form, examine, ub, ent,
						this.purchaseBillDao, this.purchaseBillItemDao,
						this.bankAccountBalanceDao, this.stockDao,
						this.stockBalanceDao, this.serialNumberDao,
						this.idGenerator);
			} catch (StockNoEnoughException arg21) {
				EncCommonHelper.setAlertMessage(request, arg21.getMessage());
				return this.showForm(request, errors, this.getFormView());
			} catch (CannotAcquireLockException arg22) {
				EncCommonHelper.setAlertMessage(request, "事务冲突故障，请重新操作！");
				return this.showForm(request, errors, this.getFormView());
			}

			alertMsg = "增加成功！";
		}

		mv.addObject("returnValue", String.valueOf(obj.getId()));
		continueFlag = request.getParameter("continue_flag");
		alertType = request.getParameter("alert_type");
		if (continueFlag != null && continueFlag.equals("1")) {
			EncCommonHelper.setAlertMessage(request, alertMsg);
			mv = new ModelAndView(
					"redirect:/purchase/PurchaseBillNew.ihtm?alert_type="
							+ alertType + "&type=" + obj.getBillType());
		} else if (continueFlag != null && continueFlag.equals("2")) {
			EncCommonHelper.setAlertMessage(request, alertMsg);
			mv = new ModelAndView(
					"redirect:/purchase/PurchaseBillNew.ihtm?alert_type="
							+ alertType + "&template_id=" + obj.getId());
		} else if (alertType == null || !alertType.equals("NONE")) {
			EncCommonHelper.setAlertMessage(request, alertMsg);
			if (alertType != null && alertType.equals("FORM")) {
				mv = new ModelAndView(new RedirectView(
						"/purchase/PurchaseBillEdit.ihtm?id=" + obj.getId()
								+ "&alert_type=" + alertType));
			}
		}

		mv.addObject("alertType", alertType);
		return mv;
	}

	public IdGenerator getIdGenerator() {
		return this.idGenerator;
	}

	public void setIdGenerator(IdGenerator idGenerator) {
		this.idGenerator = idGenerator;
	}

	public CodeRuleDao getCodeRuleDao() {
		return this.codeRuleDao;
	}

	public void setCodeRuleDao(CodeRuleDao codeRuleDao) {
		this.codeRuleDao = codeRuleDao;
	}

	public SerialNumberDao getSerialNumberDao() {
		return this.serialNumberDao;
	}

	public void setSerialNumberDao(SerialNumberDao serialNumberDao) {
		this.serialNumberDao = serialNumberDao;
	}

	public ProductDao getProductDao() {
		return this.productDao;
	}

	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao;
	}

	public DataSource getDataSource() {
		return this.dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public PurchaseBillDao getPurchaseBillDao() {
		return this.purchaseBillDao;
	}

	public void setPurchaseBillDao(PurchaseBillDao purchaseBillDao) {
		this.purchaseBillDao = purchaseBillDao;
	}

	public PurchaseBillItemDao getPurchaseBillItemDao() {
		return this.purchaseBillItemDao;
	}

	public void setPurchaseBillItemDao(PurchaseBillItemDao purchaseBillItemDao) {
		this.purchaseBillItemDao = purchaseBillItemDao;
	}

	public PurchaseBillService getPurchaseBillService() {
		return this.purchaseBillService;
	}

	public void setPurchaseBillService(PurchaseBillService purchaseBillService) {
		this.purchaseBillService = purchaseBillService;
	}

	public StorehouseDao getStorehouseDao() {
		return this.storehouseDao;
	}

	public void setStorehouseDao(StorehouseDao storehouseDao) {
		this.storehouseDao = storehouseDao;
	}

	public StockDao getStockDao() {
		return this.stockDao;
	}

	public void setStockDao(StockDao stockDao) {
		this.stockDao = stockDao;
	}

	public StockBalanceDao getStockBalanceDao() {
		return this.stockBalanceDao;
	}

	public void setStockBalanceDao(StockBalanceDao stockBalanceDao) {
		this.stockBalanceDao = stockBalanceDao;
	}

	public BankAccountBalanceDao getBankAccountBalanceDao() {
		return this.bankAccountBalanceDao;
	}

	public void setBankAccountBalanceDao(
			BankAccountBalanceDao bankAccountBalanceDao) {
		this.bankAccountBalanceDao = bankAccountBalanceDao;
	}

	public BankAccountDao getBankAccountDao() {
		return this.bankAccountDao;
	}

	public void setBankAccountDao(BankAccountDao bankAccountDao) {
		this.bankAccountDao = bankAccountDao;
	}

	public AdjustBillDao getAdjustBillDao() {
		return this.adjustBillDao;
	}

	public void setAdjustBillDao(AdjustBillDao adjustBillDao) {
		this.adjustBillDao = adjustBillDao;
	}

	public PayBillDao getPayBillDao() {
		return this.payBillDao;
	}

	public void setPayBillDao(PayBillDao payBillDao) {
		this.payBillDao = payBillDao;
	}
}